package com.mier.android.fbtalksms;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphMultiResult;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.mier.android.fbtalksms.adapter.FBFriends;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FacebookFriendsAsyncTask extends AsyncTask<Void, Void, List<GraphUser>> {
    private static String TAG = FacebookFriendsAsyncTask.class.getSimpleName();
	private Context context;
	private List<FBFriends> fbfriends;
	private List<GraphUser> graphUser;
	private FBFriendsListActivity fbactivity;
	private Session.StatusCallback sessionCallback;

	public FacebookFriendsAsyncTask(Context context, List<GraphUser> fbfriends,
			FBFriendsListActivity fbactivity,
			Session.StatusCallback sessionCallback) {
		this.context = context;
		this.graphUser = fbfriends;
		this.fbactivity = fbactivity;
		this.sessionCallback = sessionCallback;
	}

	@Override
	protected List<GraphUser> doInBackground(Void... params) {
		// TODO Auto-generated method stub
		String fql = "SELECT name,uid FROM user WHERE online_presence IN ('active', 'idle') AND uid IN ( SELECT uid2 FROM friend WHERE uid1 = me())";
		List<String> permission = new ArrayList<String>();
		permission.add("email");
		permission.add("publish_stream");
		permission.add("user_status");
		permission.add("user_online_presence");
		permission.add("friends_online_presence");
		Session session = Session.getActiveSession();
		if (session.isOpened()) {
			List<String> permissions = session.getPermissions();
			for (int i = 0; i < permissions.size(); i++) {
				Log.d("com.mier.android.FBFriendsListActivity",
						permissions.get(i));
			}

			// session.requestNewPublishPermissions(new
			// NewPermissionsRequest(this,permission));
			Bundle bundle = new Bundle();
			bundle.putString("q", fql);
			Request request = new Request(Session.getActiveSession(), "/fql",
					bundle, HttpMethod.GET, new RequestSessionCallback());
			Request.executeAndWait(request);
		} else {
			if (!session.isOpened() && !session.isClosed()) {
				session.openForRead(new Session.OpenRequest(fbactivity).setCallback(sessionCallback));
			} else {
				Session.openActiveSession(fbactivity.getParent(), true,
						sessionCallback);
			}
		}
		return graphUser;
	}

	@Override
	protected void onPostExecute(List<GraphUser> friends) {
		Log.d("com.mier.anddroid.FacebookFriendsAsyncTask", friends.toString());
		Log.d(TAG, "xxxxxx+++++" + friends.toString());
		if (this.context instanceof FBFriendsListActivity) {
			FBFriendsListActivity friendsListActivity = (FBFriendsListActivity) context;
			ListView listView = friendsListActivity.getListView();
			listView.setVisibility(View.VISIBLE);
			ArrayAdapter<GraphUser> adapter = new FbFriendsAdapter(friends);
			listView.setAdapter(adapter);
		}
	   super.onPostExecute(friends);

	}

	public class FbFriendsAdapter extends ArrayAdapter<GraphUser> {
		List<GraphUser> fbfriends;
		
		public FbFriendsAdapter(List<GraphUser> friends){
			super(fbactivity, R.layout.fbfriends_list, friends);
			this.fbfriends = friends;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return fbfriends.size();
		}

		@Override
		public GraphUser getItem(int position) {
			// TODO Auto-generated method stub
			return fbfriends.get(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View listView = convertView;
			if (listView == null) {
				listView = fbactivity.getLayoutInflater().inflate(R.layout.fbfriends_list,
						parent, false);
			}

			TextView name = (TextView) listView.findViewById(R.id.fbName);
			name.setText(fbfriends.get(position).getName());
			ImageView profile = (ImageView) listView
					.findViewById(R.id.fbProfile);
//			profile.setImageBitmap(fbfriends.get(position));

			return listView;
		}

	}

	public class RequestSessionCallback implements Request.Callback {

		@Override
		public void onCompleted(Response response) {

			try {
				System.out.println(response);
				Log.d(TAG,"+++++++"+ response.toString());
//				response.getGraphObjectList();
//				GraphObject go = response.getGraphObject();
//				JSONObject json = go.getInnerJSONObject();
//				JSONArray jArray = json.getJSONArray("data");
//				
//				FBFriends friends = null;
//				for (int i = 0; i < jArray.length(); i++) {
//					friends = new FBFriends();
//					JSONObject jObj = jArray.getJSONObject(i);
//					friends.setFbId(jObj.getString("uid"));
//					friends.setName(jObj.getString("name"));
//					friends.setFbProfile(FBFriendsListActivity.getUserPic(jObj.getString("uid")));
//					fbfriends.add(friends);
//				}
				GraphMultiResult result = response.getGraphObjectAs(GraphMultiResult.class);
				
				GraphObjectList<GraphObject> gObjList = result.getData();
				graphUser = gObjList.castToListOf(GraphUser.class);
				

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
}
